var lineReader = require('line-reader');
var fs = require('fs');
var _ = require("underscore");
var file = require('file');

var path = require('path');
var mkdirp = require('mkdirp');

function _createFile(sfilePath) {
    var dir_name = path.dirname(sfilePath);
    // origin file path
    var ori_path = path.resolve(sfilePath);
    // folder path
    var dir_path = path.resolve(dir_name);

    mkdirp.sync(dir_path);

    return fs.createWriteStream(ori_path);
}

function _fileRead(sfileName, fcall) {
    var str = "";
    lineReader.eachLine(sfileName, function(line) {
        str += line;
    }).then(function() {
        fcall(str);
    })
}

function _fileParse(sfileName, fcall) {
    var str = "";
    var array = [];
    var bmultiConfig = false;
    lineReader.eachLine(sfileName, function(line) {
        try
        {
            var obj = JSON.parse(line);
            array.push(obj);
        }
        catch (e)
        {
           
        }
    }).then(function() {
        if (array.length != 0)
            fcall(array);
        else
        {
            _fileRead(sfileName, function(str) {
                try
                {
                    var obj = JSON.parse(str);
                    fcall(obj);
                }
                catch (e)
                {

                }
            })
        }
    })
}

function _matchStartEnd(str, start, end, cb) {
    var ifrontPos = 0;
    var ibackPos = 0;

    if ((ifrontPos = str.indexOf(start)) == -1)
        cb(str);
    else
    {
        if ((ibackPos = str.indexOf(end)) == -1)
            cb(str.substr(0, ifrontPos));
        else
        {
            if (ibackPos < ifrontPos)
            {
                cb(str.substr(0, ifrontPos));
                _matchStartEnd(str.substr(ifrontPos), start, end, cb);
            }
            else
            {
                var a = str.substr(0, ifrontPos);
                var b = str.substr(ifrontPos + start.length, ibackPos - ifrontPos - start.length);
                var pos = 0;
                if ((pos = b.indexOf(start)) != -1)
                {
                    cb(str.substr(0, pos + start.length));
                    _matchStartEnd(str.substr(pos + start.length), start, end, cb);
                }
                else
                {
                    cb(a, b);
                    _matchStartEnd(str.substr(ibackPos + end.length), start, end, cb);
                }
            }
        }
    }
}

function _generateFromTemplet(stempletFile, oscope, cb) {
    var _sjavascript = "";
    var _bcodeStart = false;
    var _bcode = false;

    var _of = _createFile(oscope.of + stempletFile);
    var $$scope = oscope;
    var $$echo = function(str) {
        _of.write(str);
    }

    var self = this;
    self.$$scope = $$scope;
    
    lineReader.eachLine(stempletFile, function(line) {
        if (/```javascript/.test(line))
        {
            _bcodeStart = true;
            _bcode = false;
        }

        if (_bcode)
        {
            if (/```/.test(line))
            {
                _bcodeStart = false;
                _bcode = false;
                try
                {
                    eval(_sjavascript);
                }
                catch (e)
                {
                    
                }
            }
            else
                _sjavascript += line;
        }
        else if (_bcodeStart)
        {
            _sjavascript = "";
            _bcode = true;
            _bcodeStart = false;
        }
        else
        {
            _matchStartEnd(line, "{{", "}}", function(a, b) {
                if (a != null)
                    _of.write(a);
                if (b != null && b != "")
                {
                    try
                    {
                        _of.write(eval("(" + b + ")"));
                    }
                    catch (e)
                    {

                    }
                }
            })
        }
    }).then(function() {
        if (cb)
            cb();
    });
}

_fileParse("config.txt", function(val) {
    if (_.isArray(val))
    {
        for (var i = 0; i < val.length; i++)
        {
            _generateFromTemplet("templet.txt", val[i]);
        }
    }
    else
        _generateFromTemplet("templet.txt", val);
})
